package cn.tedu.luban.gateway.filters;

import cn.tedu.luban.gateway.enums.GatewayResultEnum;
import cn.tedu.luban.passport.protocol.common.enums.PassportResultEnum;
import com.alibaba.fastjson2.JSON;
import com.tedu.inn.protocol.exception.BusinessException;
import com.tedu.inn.protocol.model.Result;
import java.nio.charset.StandardCharsets;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * handle all the errors pakcaged in MONO
 */
@Order(-1) // 保证优先级低于默认的ResponseStatusExceptionHandler,这样能拿到响应状态码
@Component
@Slf4j
public class ErrorFilter implements ErrorWebExceptionHandler {
    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest request = exchange.getRequest();
        //记录信息
        Route route = (Route) exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR);
        log.info("route:{}", route);
        if (response.isCommitted()) {
            return Mono.error(ex);
        }
        // 将返回格式设为JSON
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        if (ex instanceof ResponseStatusException) {
            response.setStatusCode(((ResponseStatusException) ex).getStatus());
            return response.writeWith(Mono.fromSupplier(() -> {
                DataBufferFactory bufferFactory = response.bufferFactory();
                Result fail = Result.fail(GatewayResultEnum.GATEWAY_ERROR);
                log.info("fail result:{}",fail);
                log.info("route:{},request:{},message:{}", route, request,ex.getMessage());
                // 返回ErrorResult
                return bufferFactory.wrap(JSON.toJSONString(fail).getBytes(StandardCharsets.UTF_8));
            }));
        }
        if (ex instanceof BusinessException){
            // 改变请求响应返回行为
            return response.writeWith(Mono.fromSupplier(() -> {
                DataBufferFactory bufferFactory = response.bufferFactory();
                Result fail = Result.fail(GatewayResultEnum.AUTHENTICATION_ERROR);
                log.info("fail result:{}",fail);
                log.info("route:{},request:{},message:{}", route, request,ex.getMessage());
                // 返回ErrorResult
                return bufferFactory.wrap(JSON.toJSONString(fail).getBytes(StandardCharsets.UTF_8));
            }));
        }else{
            return Mono.error(ex);
        }
    }
}
